import logging

import requests
from requests.adapters import HTTPAdapter


def request_get(url, max_retries=2, timeout=5):
    # 设置重连次数
    session = requests.session()
    session.mount('http://', HTTPAdapter(max_retries=max_retries))
    session.mount('https://', HTTPAdapter(max_retries=max_retries))
    # 设置连接活跃状态为False
    session.keep_alive = False
    response = session.get(url=url, timeout=timeout)
    return response


def request_patch(url, data: dict, max_retries=2, timeout=5):
    # 设置重连次数
    session = requests.session()
    session.mount('http://', HTTPAdapter(max_retries=max_retries))
    session.mount('https://', HTTPAdapter(max_retries=max_retries))
    # 设置连接活跃状态为False
    session.keep_alive = False
    response = session.patch(url=url, data=data, timeout=timeout)
    return response


def is_token_valid(access_token):
    test_url = f'https://gitee.com/api/v5/orgs/openharmony/repos?access_token={access_token}'
    response_code = request_get(test_url).status_code
    return response_code != 401


def is_file_existence_in_remote(url_to_test):
    try:
        response = request_get(url_to_test)
    except Exception as err:
        logging.warning(f'尝试访问链接{url_to_test}失败, 失败原因：{err}')
    else:
        if response.status_code == 404:
            print(f'{url_to_test}不存在')
            return False
    return True


if __name__ == '__main__':
    pass
